const modelMapper = {};
import BaseModel from './BaseModel'
import GeneralModel from './GeneralModel'

let models = require.context('./', true, /\.js$/);
let isPrototype = (subClass, superClass) => {
  let subSuperClass = Object.getPrototypeOf(subClass);
  if (subSuperClass !== superClass) {
    if (subSuperClass !== null) {
      return isPrototype(subSuperClass, superClass)
    }
  } else {
    return true;
  }
  return false;
};
models.keys().forEach((importModule) => {
  if (importModule.indexOf('index') > -1) {
    return false;
  }
  const module = models(importModule).default;
  if (isPrototype(module, BaseModel)) {
    modelMapper[module.type] = module;
  }
});

export default class DataModel {
  static buildModel(type, initData = null) {
    if (this.hasModel(type)) {
      return new modelMapper[type](initData);
    } else {
      return new GeneralModel(initData);
    }

  }

  static hasModel(type) {
    return modelMapper.hasOwnProperty(type);
  }

}
